package com.sinosoft.ci.utils;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.tmatesoft.svn.core.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.wc.ISVNOptions;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

public class EasySvnClient {
	private SVNClientManager svnClientManager;
	private SVNURL svnurl;
	
	public EasySvnClient(String svnurl,String username, String password){
		
		try{
			SVNURL url = SVNURL.parseURIEncoded(svnurl);
			this.svnurl = url;
			
			ISVNAuthenticationManager authenManager = SVNWCUtil.createDefaultAuthenticationManager(null,username, password);
			ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
			
			svnClientManager = SVNClientManager.newInstance(options, authenManager);
		}catch(Exception ex){
			throw new RuntimeException("SVN 客户端初始化失败！",ex);
		}
	} 
	
	/**
	 * 获取特定版本的文件变化清单
	 * 
	 * @param version
	 * @return
	 */
	public String[] getFileChangedList(long version) throws SVNException{
		return getFileChangedList(version,"/");
	}
	
	public String[] getFileChangedList(long version,String path) throws SVNException{
		SVNLogClient logClient = svnClientManager.getLogClient();
		SVNRevision revision = SVNRevision.create(version);
		
		ListSVNLogEntryHandler handler = new ListSVNLogEntryHandler();
		logClient.doLog(svnurl, new String[]{path}, revision, revision, revision,
				false, true,false, 1, null, handler);
		return handler.getEntrys();
	}
	
	private class ListSVNLogEntryHandler implements ISVNLogEntryHandler{
		private List<String> entrys = new LinkedList<String>();

		@Override
		public void handleLogEntry(SVNLogEntry entry)
				throws SVNException {
			Map<String,SVNLogEntryPath> paths = entry.getChangedPaths();
			
			for(Map.Entry<String, SVNLogEntryPath> e : paths.entrySet()){
				SVNLogEntryPath entryPath = e.getValue();
				
				System.out.println(e.getKey() + ":" + entryPath.getKind() + ":" + entryPath.getCopyRevision() + ":" + entryPath.getCopyPath());
				
				SVNNodeKind nodeKind = entryPath.getKind();
				if(SVNNodeKind.FILE.equals(nodeKind)){
					entrys.add(e.getKey());
				}
			}
		}
		
		public String[] getEntrys(){
			return entrys.toArray(new String[entrys.size()]);
		}
	}
}
